#!/usr/bin/python2.5
# Copyright (c) 2008 MalFind

__author__ = "mavrommatis@gmail.com (Panayiotis Mavrommatis)"

import cgi
import logging
import os

import handler_lib
from model import models

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class Stats(webapp.RequestHandler):
  '''Handles a /stats request.'''

  def get(self):
    '''Handles a get request.'''
    queries = db.GqlQuery(
      'SELECT * FROM Query ORDER BY when DESC LIMIT 10').fetch(10)
    digests = db.GqlQuery(
      'SELECT * FROM Digest LIMIT 10').fetch(10)
    values = {
      'queries': queries, 'digests': digests,
      'userdata': handler_lib.GetUserData()
    }
    path = os.path.join(os.path.dirname(__file__), 'html/stats.html')
    self.response.out.write(template.render(path, values))


  def post(self):
    '''Handles a post request.'''
    # We allow an admin to add a digest. Use only on local environment
    # for testing.
    hash = self.request.get("digest")
    if model.models.Digest.gql("WHERE hash = :1", hash).get() is None:
      digest = model.models.Digest(hash=hash)
      digest.put()

    logging.info("Added digest %s" % hash)
    self.response.out.write('<html><body>Added:<pre>')
    self.response.out.write(cgi.escape(hash))
    self.response.out.write('</pre></body></html>')
